package com.by.interceptor;

import com.by.bean.UserInfo;
import com.by.context.UserContext;
import com.by.token.TokenTemplate;
import com.by.token.ValidResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {

    TokenTemplate tokenTemplate;

    public TokenInterceptor(TokenTemplate tokenTemplate) {
        this.tokenTemplate = tokenTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //获取token
//        String token = request.getHeader("token");
//        if (null == token) {
//            //用户没传 无取访问
//            fail(response, "没有token,无取访问");
//            return false;
//        }
//        //传了token 验证
//        ValidResult result = tokenTemplate.valid(token);
//        if (result != ValidResult.VALID) {
//            fail(response, result.toString());
//            return false;
//        }
        //设置模拟用户信息
        UserInfo userInfo=new UserInfo(1,"admin",1,11);
        UserContext.set(userInfo);
        return true;
    }

    void fail(HttpServletResponse response, String msg) {
        //设置中文
        response.setContentType("application/json;charset=utf-8");
        //获取输出流  jdk8  资源 自动释放
        try (PrintWriter pw = response.getWriter();) {
            pw.write("{\"code\":0,\"msg\":\"" + msg + "\"}");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
